package org.jet.emall.security.handler;

import com.alibaba.fastjson.JSON;
import org.jet.emall.common.restful.result.CommonResult;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败时回调
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-07 20:13
 */
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    /**
     * 登录失败时回调此方法，给用户返回登录失败提示信息的逻辑都在这里实现
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        CommonResult<Object> result = null;

        //密码无效
        if(exception instanceof BadCredentialsException){
            result = CommonResult.notFound("密码不正确");
        }else if (exception instanceof UsernameNotFoundException){
            //用户不存在
            result = CommonResult.notFound("用户不存在");
        }else if( exception instanceof LockedException){
            //用户被锁定
            result = CommonResult.notFound("用户帐号被锁定");
        }else if( exception instanceof DisabledException) {
            //用户禁用
            result = CommonResult.notFound("用户帐号被禁用");
        }else if( exception instanceof AccountExpiredException) {
            result = CommonResult.notFound("用户帐号已过期");
        }else if( exception instanceof CredentialsExpiredException){
            result = CommonResult.notFound("用户密码已过期");
        }else {
            //其它异常
            result = CommonResult.notFound("服务器内部错误,请稍后再试");
        }
        exception.printStackTrace();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write( JSON.toJSONString(result) );
        response.flushBuffer();
    }
}
